package render

import (
	"cloud-entropy-storage-system/common/pkg/resp"
	"github.com/gin-gonic/gin"
	"path"
	"strconv"
)

func (r *Render) FileList() gin.HandlerFunc {
	return func(c *gin.Context) {
		resp.BuildTpl(c, "file_list").WriteTpl()
	}
}

func (r *Render) Upload() gin.HandlerFunc {
	return func(c *gin.Context) {
		dir := c.DefaultQuery("dir", "")
		server := "/api/upload/"
		if dir != "" {
			server = path.Join(server, dir)
		}
		resp.BuildTpl(c, "file_upload").WriteTpl(gin.H{"dir": dir, "server": server})
	}
}

func (r *Render) Gallery() gin.HandlerFunc {
	return func(c *gin.Context) {
		dir := c.DefaultQuery("dir", "")
		page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
		data, err := r.fileSvc.Gallery(page, 10, r.cfg.HttpHost, dir)
		if err != nil {
			resp.ErrorTpl(c).WriteTpl()
			return
		}
		if data == nil {
			resp.BuildTpl(c, "file_gallery").WriteTpl(gin.H{"img": nil, "pageCount": 0, "page": page})
		} else {
			resp.BuildTpl(c, "file_gallery").WriteTpl(gin.H{"img": data.ImgUrl, "count": data.Count, "page": data.CurrentPage})
		}
	}
}

func (r *Render) Video() gin.HandlerFunc {
	return func(c *gin.Context) {
		fp := c.DefaultQuery("fp", "")
		if fp == "" {
			resp.ErrorTpl(c).WriteTpl()
			return
		}
		resp.BuildTpl(c, "xgplayer").WriteTpl(gin.H{"fp": fp})
	}
}
